<template>
  <div style="width: 100%">
    <div v-if="props.type == 'file'" style="width: 100%">
      <el-button type="primary" plain @click="chooseFile" v-show="showBtn">
        <el-icon> <Upload /> </el-icon>上传文件
      </el-button>
      <div v-if="props.showFile">
        <div
          v-for="(item, index) in myFileList"
          :key="item.ID"
          :class="props.showSort && props.showBtn ? 'pdt10' : ''"
        >
          <div
            v-show="imgType.includes(item.Suffix)"
            class="rowBox flex acenter"
          >
            <div v-if="!props.mobile">
              <el-popover
                class="imgbox"
                placement="left"
                :width="200"
                trigger="hover"
              >
                <el-image
                  :src="item.url"
                  fit="fill"
                  :initial-index="filterIndex(item)"
                  preview-teleported
                  :preview-src-list="srcList"
                >
                </el-image>
                <template #reference>
                  <div
                    class="fileName"
                    type="primary"
                    slot="reference"
                    @click="downLoadFile(item)"
                  >
                    {{ item.Name }}
                  </div>
                </template>
              </el-popover>
            </div>
            <div v-else>
              <div class="overShow fileName" @click="downLoadFile(item)">
                {{ item.Name }}
              </div>
            </div>
            <div v-if="props.detail && props.showSort && !props.mobile">
              {{ item.Remark }}
            </div>
            <div
              class="flex acenter"
              v-if="props.showSort && !props.detail && !props.mobile"
              style="width: 100%"
            >
              <span class="mgl10 wkeep">排序:</span>
              <el-input-number
                v-model="item.Sort"
                placeholder="排序"
                v-number
                style="width: 160px !important"
                @input="handleSortInput"
                controls-position="right"
              />
              <span class="mgl10 wkeep">备注:</span>
              <el-input
                style="width: 100%"
                clearable
                @input="handleSortInput"
                v-model="item.Remark"
                placeholder="备注"
              ></el-input>
            </div>
            <el-link type="danger" :underline="false">
              <el-icon
                v-if="showBtn"
                class="mgl10"
                :size="16"
                @click="deleteFile(index)"
                ><DeleteFilled
              /></el-icon>
            </el-link>
          </div>
          <div v-show="!imgType.includes(item.Suffix)">
            <div class="rowBox flex">
              <div class="overShow fileName" @click="downLoadFile(item)">
                {{ item.Name }}
              </div>
              <div
                class="flex acenter"
                v-if="props.detail && props.showSort && !props.mobile"
              >
                备注:{{ item.Remark }}
              </div>
              <div
                class="flex acenter"
                v-if="props.showSort && !props.detail && !props.mobile"
                style="width: 100%"
              >
                <span class="mgl10 wkeep">排序:</span>
                <el-input-number
                  v-model="item.Sort"
                  placeholder="排序"
                  v-number
                  style="width: 160px !important"
                  @input="handleSortInput"
                  controls-position="right"
                />
                <span class="mgl10 wkeep">备注:</span>
                <el-input
                  style="width: 100%"
                  clearable
                  v-model="item.Remark"
                  @input="handleSortInput"
                  placeholder="备注"
                ></el-input>
              </div>
              <el-link type="danger" :underline="false">
                <el-icon
                  v-if="showBtn"
                  class="mgl10"
                  :size="16"
                  @click="deleteFile(index)"
                  ><DeleteFilled
                /></el-icon>
              </el-link>
            </div>
          </div>
          <div v-if="props.mobile && props.showSort">
            <div v-show="!props.detail">
              <el-input
                style="width: 30%"
                clearable
                v-number
                @input="handleSortInput"
                v-model.number="item.Sort"
                placeholder="排序"
              ></el-input>
              <el-input
                style="width: 70%"
                clearable
                @input="handleSortInput"
                v-model="item.Remark"
                placeholder="备注"
              ></el-input>
            </div>
            <div v-show="props.detail">
              <div>备注：{{ item.Remark }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="props.type == 'img'">
      <div class="content">
        <div
          v-for="(item, index) in myFileList"
          class="imgItem"
          @mouseenter="activeImg = index"
          @mouseleave="activeImg = -1"
        >
          <el-image
            :src="item.url"
            fit="fill"
            :initial-index="filterIndex(item)"
            preview-teleported
          >
          </el-image>
          <div class="preMask" v-if="activeImg == index">
            <div
              class="myIcon pointer"
              v-if="iconList.includes('setImg')"
              @click="getImgItem(item)"
            >
              <el-tooltip
                class="box-item"
                effect="dark"
                content="设置展示图"
                placement="top-start"
              >
                <el-icon color="white" :size="26"><House /></el-icon>
              </el-tooltip>
            </div>
            <div
              class="myIcon pointer"
              v-if="iconList.includes('preview')"
              @click="preViewImage(item)"
            >
              <el-tooltip
                class="box-item"
                effect="dark"
                content="预览"
                placement="top-start"
              >
                <el-icon color="white" :size="26"><View /></el-icon>
              </el-tooltip>
            </div>
            <div
              class="myIcon pointer"
              v-if="iconList.includes('delete')"
              @click="deleteFile(index)"
            >
              <el-tooltip
                class="box-item"
                effect="dark"
                content="删除"
                placement="top-start"
              >
                <el-icon color="white" :size="26"><Delete /></el-icon>
              </el-tooltip>
            </div>
          </div>
        </div>
        <div class="chooseBtn" v-show="!props.detail" @click="chooseFile">
          <el-icon :size="40" color="#b8b5b5"><Plus /></el-icon>
        </div>
      </div>
      <el-dialog
        v-model="dialogVisible"
        title="预览"
        width="800px"
        append-to-body
        draggable
      >
        <img
          :src="dialogImageUrl"
          style="display: block; max-width: 100%; margin: 0 auto"
        />
      </el-dialog>
    </div>
    <input
      type="file"
      ref="inputRef"
      v-show="false"
      :accept="formatAccept()"
      :multiple="props.multiple"
    />
  </div>
</template>

<script setup name="FileUpload">
import {
  getCurrentInstance,
  onActivated,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue';
import { uploadApi } from '@/api/upload/index';
import { saveAs } from 'file-saver';
const { proxy } = getCurrentInstance();
const emit = defineEmits([
  'update:fileList',
  'fileListFun',
  'getImgItem',
  'getItem'
]);
const props = defineProps({
  detail: {
    default: true
  },
  type: {
    default: 'file'
  },
  showBtn: {
    type: Boolean,
    default: true
  },
  //自定义字段专用
  fileList: {
    default: []
  },
  isCustom: {
    default: false
  },
  limt: {
    default: 4
  },
  getType: {
    default: 'item'
  },
  iconList: {
    default: ['preview', 'delete']
  },
  showSort: {
    default: false
  },
  mobile: {
    default: false
  },
  showFile: {
    default: true
  },
  limitType: {
    default: []
  },
  multiple: {
    default: true
  }
});
//data
const imgType = ref(['.jpg', '.jpeg', '.png']);
const myFileList = ref([]);
const srcList = ref([]);
const activeImg = ref(-1);
const dialogVisible = ref(false);
const dialogImageUrl = ref();
const inputRef = ref();

watch(
  () => props.fileList,
  (n, o) => {
    let list = n.length ? proxy.$deepClone(n) : [];
    list?.forEach(async (item, index) => {
      if (imgType.value.includes(item.Suffix)) {
        try {
          let url = proxy.$addFileHead(item.Path);
          srcList.value.push(url);
          item.url = url;
          item.Sort = index;
        } catch (error) {
          console.log(error);
        }
      }
      item.Name = proxy.$filterSuffix(item.Name, item.Suffix);
    });
    myFileList.value = list;
  },
  {
    immediate: true,
    deep: true
  }
);
onMounted(() => {
  inputRef.value.addEventListener('change', e => {
    console.log(e.target.files);
    let limitType = formatAccept();
    let fileList = Array.from(e.target.files);
    if (myFileList.value.length == props.limt && props.limt != 1) {
      return proxy.$modal.msgError('文件限制' + props.limt + '个');
    }
    fileList?.every(async item => {
      try {
        let Suffix = item.name.slice(item.name.lastIndexOf('.'));
        if (!limitType.includes(Suffix) && !limitType.includes('*')) {
          proxy.$modal.msgError(
            item.name + ' 上传失败! 文件类型限制：' + limitType
          );
          return false;
        }
        console.log(item);
        let res = await uploadApi(item);
        let url = proxy.$addFileHead(res.data.Path);
        if (imgType.value.includes(Suffix)) {
          srcList.value.push(url);
        }
        myFileList.value.push({
          ID: res.data.ID,
          FileID: res.data.ID,
          Name: item.name,
          Suffix: Suffix,
          url,
          Path: url,
          Sort: myFileList.value.length,
          Size: item.size,
          SizeKb: Math.ceil(item.size / 1024)
        });
        emit('update:fileList', myFileList.value);

        if (myFileList.value.length > props.limt && props.limt != 1) {
          myFileList.value.splice(props.limt);
          proxy.$modal.msgError('文件限制' + props.limt + '个');
          return false;
        } else if (props.limt == 1) {
          myFileList.value = [myFileList.value.at(-1)];
          emit('update:fileList', myFileList.value);
        }
      } catch (error) {
        proxy.$modal.msgError('上传失败! ' + error);
        emit('update:fileList', myFileList.value);
        console.log(error);
      }
    });
    inputRef.value.value = [];
    emit('getItem', myFileList.value);
  });
});
function formatAccept() {
  let limitType = [];
  if (props.type == 'img') {
    limitType = imgType.value;
  } else if (props.limitType?.length) {
    limitType = props.limitType;
  } else {
    limitType = ['*'];
  }
  return limitType;
}

const chooseFile = () => {
  inputRef.value.click();
};

function handleSortInput() {
  emit('update:fileList', myFileList.value);
}

const deleteFile = index => {
  // myFileList.value = myFileList.value?.filter((item) => item.ID != ID);
  myFileList.value.splice(index, 1);
  emit('update:fileList', myFileList.value);
};
function filterIndex(item) {
  return srcList.value.indexOf(item.url);
}
function preViewImage(item) {
  dialogVisible.value = true;
  dialogImageUrl.value = item.url;
}
async function downLoadFile(item) {
  let url = proxy.$addFileHead(item.Path);
  let name = proxy.$filterSuffix(item.Name, item.Suffix);
  try {
    window.open(url);
    // saveAs(url);
  } catch (error) {
    console.log(error);
  }
}

function getImgItem(item) {
  item.removeHeadUrl = proxy.$removeFileHead(item.url);
  emit('getImgItem', item);
}
</script>

<style lang="scss" scoped>
.fileName {
  color: $color;
  word-break: keep-all;
  white-space: nowrap;
  cursor: pointer;
  line-height: 32px;
  // min-width: 160px;
  max-width: 160px;
  &:hover {
    color: #79bbff;
  }
}

.deleteIcon {
  margin-left: 20px;

  &:hover {
    color: red;
    cursor: pointer;
  }
}

.rowBox {
  line-height: 26px;
}
:deep(.el-link) {
  line-height: 26px;
}
.content {
  display: flex;
  flex-wrap: wrap;
  .imgItem {
    width: 148px;
    height: 148px;
    border-radius: 6px;
    overflow: hidden;
    margin-right: 10px;
    margin-bottom: 10px;
    position: relative;
    :deep(.el-image) {
      height: 100%;
      width: 100%;
    }
    .preMask {
      position: absolute;
      left: 0;
      top: 0;
      z-index: 100;
      width: 148px;
      height: 148px;
      border-radius: 6px;
      overflow: hidden;
      background-color: rgba($color: #000000, $alpha: 0.4);
      display: flex;
      align-items: center;
      justify-content: center;
      .myIcon {
        & + .myIcon {
          margin-left: 10px;
        }
      }
    }
  }
  .chooseBtn {
    width: 148px;
    height: 148px;
    border: 1px dashed #b8b5b5;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    &:hover {
      border-color: $color;
    }
  }
}
</style>
